package com.paishen.peiniwan.module.square;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;

import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Banner;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.common.widget.MaterialHeader;
import com.paishen.peiniwan.module.MainActivity;
import com.paishen.peiniwan.module.date.DateStartActivity;
import com.paishen.peiniwan.module.profile.ProfileInfoActivity;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;


public class MainSquareLayout extends FrameLayout {
    private SquareFilterDialog dlgSquareFilter;

    private final PtrFrameLayout layPtrFrame;
    private final SquareAdapter adapter;
    private final RecyclerView viewRecycler;
    private final LinearLayoutManager layoutManager;

    private boolean reqLoad = false;
    private int currPage = 1;
    private boolean fetchOver = false;
    private int filterGender;
    private String filterOrder;

    public MainSquareLayout(Context context) {
        this(context, null);
    }

    public MainSquareLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 过滤条件
        filterGender = App.i().getUser().getGender() ? PnwHttpManager.Square.SQUARE_FILTER_GENDER_FEMALE : PnwHttpManager.Square.SQUARE_FILTER_GENDER_MALE;
        filterOrder = PnwHttpManager.Square.SQUARE_FILTER_TYPE_RECENT_LOGIN;

        LayoutInflater.from(context).inflate(R.layout.layout_main_square, this);
        getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
        header.setPtrFrameLayout(layPtrFrame);
        // layPtrFrame.setPinContent(true);
        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.setResistance(2.5f);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                currPage = 1;
                requestSquareGetBanner();
            }
        });

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(layoutManager = new LinearLayoutManager(context));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter = new SquareAdapter());
        viewRecycler.setAdapter(alphaAdapter);
        viewRecycler.setItemAnimator(null);

        viewRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private boolean scrollDown = false;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollDown = dy > 0;
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        adapter.startBannerAutoSliding();
                        int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = layoutManager.getItemCount();
                        if (lastVisibleItem >= (totalItemCount - 1) && scrollDown) {
                            if (!fetchOver) requestSquareIndex();
                        }
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        adapter.stopBannerAutoSliding();
                        break;
                }
            }
        });

        requestSquareGetBanner();
    }

    public void showSquareFilterDialog() {
        if (dlgSquareFilter == null) {
            SquareFilterDialog.Builder builder = new SquareFilterDialog.Builder(getContext());
            builder.setOnItemSelectedListener(new SquareFilterDialog.OnItemSelectedListener() {
                @Override
                public void onItemSelected(Object[] items) {
                    filterGender = (int) items[0];
                    filterOrder = (String) items[1];
                    currPage = 1;

                    int hasLocationPermission = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION);
                    if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions((Activity) getContext(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                MainActivity.CODE_FOR_LOCATION_PERMISSION);
                        return;
                    }

                    requestSquareIndex();

                }
            });
            builder.setDefaultGender(App.i().getUser().getGender());
            dlgSquareFilter = builder.create();
        }
        dlgSquareFilter.show();
    }


    public void startAnimation() {
        adapter.startBannerAutoSliding();
    }

    public void stopAnimation() {
        adapter.stopBannerAutoSliding();
    }

    private static final class SquareAdapter extends RecyclerView.Adapter {
        public static final ColorDrawable[][] background_default = new ColorDrawable[][]{
                new ColorDrawable[]{new ColorDrawable(0xFFE65C5C), new ColorDrawable(0xFFA2DCE8), new ColorDrawable(0xFFE68A8B)},
                new ColorDrawable[]{new ColorDrawable(0xFFBFE673), new ColorDrawable(0xFFE6739A), new ColorDrawable(0xFFA27DB3)},
                new ColorDrawable[]{new ColorDrawable(0xFFE67273), new ColorDrawable(0xFFE6C689), new ColorDrawable(0xFF405580)},
                new ColorDrawable[]{new ColorDrawable(0xFF655266), new ColorDrawable(0xFF58A4B2), new ColorDrawable(0xFFE6D273)},
        };

        public static final int FETCH_COUNT = 21;

        static class SquareElement {
            public static final int TYPE_BANNER = 1;
            public static final int TYPE_ITEM = 2;
            public static final int TYPE_LOAD = 3;
            public int type;
            public Object element;
        }

        private final SquareAdapter.SquareElement seLoad;
        private SquareAdapter.SquareElement seBanner;

        private final List<SquareElement> squareElements = new ArrayList<>();
        private BannerLayout layBanner;

        SquareAdapter() {
            seLoad = new SquareAdapter.SquareElement();
            seLoad.type = SquareAdapter.SquareElement.TYPE_LOAD;
            seLoad.element = true;
        }

        public void setBanner(List<Banner> listBanner) {
            if (listBanner != null && listBanner.size() > 0) {
                SquareAdapter.SquareElement seBanner = new SquareAdapter.SquareElement();
                seBanner.type = SquareElement.TYPE_BANNER;
                seBanner.element = listBanner;
                this.seBanner = seBanner;

                if (squareElements.size() > 0) {
                    squareElements.set(0, seBanner);
                    notifyItemChanged(0);
                } else {
                    squareElements.add(seBanner);
                    notifyItemInserted(0);
                }
            }
        }

        public boolean refreshLoadState(boolean shown) {
            if (squareElements.size() > 0) {
                seLoad.element = shown;
                int loadIdx = squareElements.indexOf(seLoad);
                if (loadIdx >= 0) {
                    notifyItemChanged(loadIdx);
                }
                return true;
            }
            return false;
        }

        public boolean set(List<SquareElement> dataList, boolean fetchOver) {
            squareElements.clear();
            if (seBanner != null) squareElements.add(seBanner);
            squareElements.addAll(dataList);
            if (!fetchOver) squareElements.add(seLoad);
            notifyDataSetChanged();
            return true;
        }

        public boolean append(List<SquareElement> dataList, boolean fetchOver) {
            if (dataList != null && dataList.size() > 0 && squareElements.size() > 1) {
                int loadIdx = squareElements.indexOf(seLoad);
                if (loadIdx >= 0) {
                    squareElements.remove(loadIdx);
                    notifyItemRemoved(loadIdx);
                }
                squareElements.addAll(dataList);
                if (!fetchOver) squareElements.add(seLoad);
                notifyItemRangeInserted(loadIdx, dataList.size() + 1);
                return true;
            }
            return false;
        }

        public void stopBannerAutoSliding() {
            if (layBanner != null) layBanner.stopAutoSliding();
        }

        public void startBannerAutoSliding() {
            if (layBanner != null) layBanner.startAutoSliding();
        }

        public class ViewHolderBanner extends RecyclerView.ViewHolder {
            public ViewHolderBanner(View view) {
                super(view);
            }

            public BannerLayout layBanner;
        }

        public class ViewHolderItem extends RecyclerView.ViewHolder {
            public ViewHolderItem(View view) {
                super(view);
            }

            public SquareImageLayout laySquareImage1, laySquareImage2, laySquareImage3;
        }

        public class ViewHolderLoad extends RecyclerView.ViewHolder {
            public ViewHolderLoad(View view) {
                super(view);
            }
        }

        @Override
        public int getItemCount() {
            return squareElements.size();
        }

        @Override
        public int getItemViewType(int position) {
            return squareElements.get(position).type;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            switch (type) {
                case SquareElement.TYPE_BANNER:
                    View viewBanner = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_main_square_banner, viewGroup, false);
                    ViewHolderBanner vhBanner = new ViewHolderBanner(viewBanner);
                    vhBanner.layBanner = (BannerLayout) viewBanner.findViewById(R.id.lay_banner);
                    layBanner = vhBanner.layBanner;
                    return vhBanner;
                case SquareElement.TYPE_ITEM:
                    View viewItem = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_main_square_item, viewGroup, false);
                    ViewHolderItem vhItem = new ViewHolderItem(viewItem);
                    vhItem.laySquareImage1 = (SquareImageLayout) viewItem.findViewById(R.id.lay_square_image_1);
                    vhItem.laySquareImage1.setOnClickListener(onUserInfoClickListener);
                    vhItem.laySquareImage2 = (SquareImageLayout) viewItem.findViewById(R.id.lay_square_image_2);
                    vhItem.laySquareImage2.setOnClickListener(onUserInfoClickListener);
                    vhItem.laySquareImage3 = (SquareImageLayout) viewItem.findViewById(R.id.lay_square_image_3);
                    vhItem.laySquareImage3.setOnClickListener(onUserInfoClickListener);
                    return vhItem;
                case SquareElement.TYPE_LOAD:
                    View viewLoad = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.frame_recycler_load, viewGroup, false);
                    return new ViewHolderLoad(viewLoad);
                default:
                    throw new IllegalArgumentException("MainSquareLayout error type :" + type);
            }
        }

        private final OnClickListener onUserInfoClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                User user = (User) v.getTag();
                if (user != null){
                    Intent intent = new Intent(v.getContext(), ProfileInfoActivity.class);
                    intent.putExtra(ProfileInfoActivity.EXTRA_SHOWN_USER_ID, user.id);
                    v.getContext().startActivity(intent);
                }
            }
        };

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
            final SquareElement se = squareElements.get(position);
            switch (se.type) {
                case SquareElement.TYPE_BANNER:
                    ViewHolderBanner vhBanner = (ViewHolderBanner) viewHolder;
                    vhBanner.layBanner.setData((List<Banner>) se.element);
                    break;
                case SquareElement.TYPE_ITEM:
                    ViewHolderItem vhItem = (ViewHolderItem) viewHolder;
                    int fixPosition = (position - 1) % 4;

                    SquareElement seItem = squareElements.get(position);
                    List<User> userList = (List<User>) seItem.element;
                    if (userList != null) {
                        vhItem.laySquareImage1.setVisibility(View.INVISIBLE);
                        vhItem.laySquareImage1.setTag(null);
                        vhItem.laySquareImage2.setVisibility(View.INVISIBLE);
                        vhItem.laySquareImage2.setTag(null);
                        vhItem.laySquareImage3.setVisibility(View.INVISIBLE);
                        vhItem.laySquareImage3.setTag(null);
                        switch (userList.size()) {
                            default:
                            case 3:
                                vhItem.laySquareImage3.setVisibility(View.VISIBLE);
                                vhItem.laySquareImage3.setData(userList.get(2), background_default[fixPosition][2]);
                                vhItem.laySquareImage3.setTag(userList.get(2));
                            case 2:
                                vhItem.laySquareImage2.setVisibility(View.VISIBLE);
                                vhItem.laySquareImage2.setData(userList.get(1), background_default[fixPosition][1]);
                                vhItem.laySquareImage2.setTag(userList.get(1));
                            case 1:
                                vhItem.laySquareImage1.setVisibility(View.VISIBLE);
                                vhItem.laySquareImage1.setData(userList.get(0), background_default[fixPosition][0]);
                                vhItem.laySquareImage1.setTag(userList.get(0));
                            case 0:
                                break;
                        }
                    }
                    break;
                case SquareElement.TYPE_LOAD:
                    ViewHolderLoad vhLoad = (ViewHolderLoad) viewHolder;
                    vhLoad.itemView.setVisibility(((boolean) seLoad.element) ? View.VISIBLE : View.GONE);
                    break;
            }
        }
    }

    private void requestSquareGetBanner() {
        PnwHttpManager.Square.getbanner(((BaseActivity) getContext()).TAG, new PnwOkCallbackAdapter<HttpRespData<List<Banner>>>() {
            @Override
            public void onResponse(HttpRespData<List<Banner>> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    if (response.data != null) {
                        adapter.setBanner(response.data);
                        currPage = 1;
                        requestSquareIndex();
                    }
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                //
            }
        });
    }

    public void requestSquareIndex() {
        if (dlgSquareFilter != null) dlgSquareFilter.dismiss();

        final int page = currPage;
        if (reqLoad) return;
        reqLoad = true;

        if (page < 2 && TextUtils.equals(PnwHttpManager.Square.SQUARE_FILTER_TYPE_RECENTLY, filterOrder)) {
            // 启动定位
            App.i().locationAsync(new PnwOkCallbackAdapter<HttpResp>() {
                @Override
                public void onResponse(HttpResp response, boolean fresh) {
                    super.onResponse(response, fresh);
                    adapter.refreshLoadState(true);
                    PnwHttpManager.Square.index(((BaseActivity) getContext()).TAG, filterGender, filterOrder, page, new PnwOkCallbackAdapter<HttpRespData<List<User>>>() {
                        @Override
                        public void onResponse(HttpRespData<List<User>> response, boolean fresh) {
                            super.onResponse(response, fresh);
                            layPtrFrame.refreshComplete();
                            reqLoad = false;
                            fetchOver = false;
                            if (response.errcode == C.http.RESULT_SUCCESS) {
                                if (response.data != null && response.data.size() > 0) {
                                    List<SquareAdapter.SquareElement> sItems = new ArrayList<>();
                                    for (int row = 0; row < response.data.size(); row = row + 3) {
                                        SquareAdapter.SquareElement s606 = new SquareAdapter.SquareElement();
                                        s606.type = SquareAdapter.SquareElement.TYPE_ITEM;
                                        List<User> rows = new ArrayList<>();
                                        if (row < response.data.size())
                                            rows.add(response.data.get(row));
                                        if (row + 1 < response.data.size())
                                            rows.add(response.data.get(row + 1));
                                        if (row + 2 < response.data.size())
                                            rows.add(response.data.get(row + 2));

                                        s606.element = rows;
                                        sItems.add(s606);
                                    }

                                    fetchOver = response.data.size() < SquareAdapter.FETCH_COUNT;
                                    if (!fetchOver) currPage = currPage + 1;
                                    boolean b = page != 1 ? adapter.append(sItems, fetchOver) : adapter.set(sItems, fetchOver);
                                } else {
                                    BaseUtil.showToast(response.errmsg);
                                    fetchOver = true;
                                    boolean b = page != 1 ? adapter.refreshLoadState(false) : adapter.set(new ArrayList<SquareAdapter.SquareElement>(), true);
                                }
                            } else {
                                if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                                    BaseUtil.showToast(response.errmsg);
                                }

                                adapter.refreshLoadState(false);
                            }
                        }

                        @Override
                        public void onFailure(Request request, Exception e) {
                            super.onFailure(request, e);
                            layPtrFrame.refreshComplete();
                            reqLoad = false;
                            adapter.refreshLoadState(false);
                        }
                    });
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    // super.onFailure(request, e);  //高德定位失败，不走父类提示
                    BaseUtil.showToast(R.string.square_loc_fail);
                    filterOrder = PnwHttpManager.Square.SQUARE_FILTER_TYPE_RECENT_LOGIN;

                    if (getContext() instanceof MainActivity) {
                        MainActivity act = (MainActivity) getContext();
                        act.showLocRetryDialog();
                    }

                    layPtrFrame.refreshComplete();
                    reqLoad = false;
                    adapter.refreshLoadState(false);
                }
            });
        } else {
            adapter.refreshLoadState(true);
            PnwHttpManager.Square.index(((BaseActivity) getContext()).TAG, filterGender, filterOrder, page, new PnwOkCallbackAdapter<HttpRespData<List<User>>>() {
                @Override
                public void onResponse(HttpRespData<List<User>> response, boolean fresh) {
                    super.onResponse(response, fresh);
                    layPtrFrame.refreshComplete();
                    reqLoad = false;
                    fetchOver = false;
                    if (response.errcode == C.http.RESULT_SUCCESS) {
                        if (response.data != null && response.data.size() > 0) {
                            List<SquareAdapter.SquareElement> sItems = new ArrayList<>();
                            for (int row = 0; row < response.data.size(); row = row + 3) {
                                SquareAdapter.SquareElement s606 = new SquareAdapter.SquareElement();
                                s606.type = SquareAdapter.SquareElement.TYPE_ITEM;
                                List<User> rows = new ArrayList<>();
                                if (row < response.data.size())
                                    rows.add(response.data.get(row));
                                if (row + 1 < response.data.size())
                                    rows.add(response.data.get(row + 1));
                                if (row + 2 < response.data.size())
                                    rows.add(response.data.get(row + 2));

                                s606.element = rows;
                                sItems.add(s606);
                            }

                            fetchOver = response.data.size() < SquareAdapter.FETCH_COUNT;
                            if (!fetchOver) currPage = currPage + 1;
                            boolean b = page != 1 ? adapter.append(sItems, fetchOver) : adapter.set(sItems, fetchOver);
                        } else {
                            BaseUtil.showToast(response.errmsg);
                            fetchOver = true;
                            boolean b = page != 1 ? adapter.refreshLoadState(false) : adapter.set(new ArrayList<SquareAdapter.SquareElement>(), true);
                        }
                    } else {
                        if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                                response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                            BaseUtil.showToast(response.errmsg);
                        }

                        adapter.refreshLoadState(false);
                    }
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    super.onFailure(request, e);
                    layPtrFrame.refreshComplete();
                    reqLoad = false;
                    adapter.refreshLoadState(false);
                }
            });
        }
    }

}
